package com.wiz.weixin.controllor;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wiz.weixin.common.GlobalConstant;
import com.wiz.weixin.common.TencentConstant;
import com.wiz.weixin.manager.AgentManager;
import com.wiz.weixin.manager.CodeManager;
import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.util.JSSDKUtil;
import com.wiz.weixin.util.TencentUtil;
import com.wiz.weixin.util.WxMessageUtil;

@Controller
@RequestMapping("/tencent")
public class TencentControllor {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private TencentManager tencentManager;
	@Resource
	private AgentManager agentManager;
	@Resource
	private CodeManager codeManager;
	
	@RequestMapping(value="", method=RequestMethod.GET)
	@ResponseBody
	public String signature(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model){
		String signature = request.getParameter("signature");//签名串
		String timestamp =  request.getParameter("timestamp");//时间戳
		String nonce =  request.getParameter("nonce"); //随机数
		String echostr =  request.getParameter("echostr"); //随机字符串
		boolean b = TencentUtil.checkSignature(signature, timestamp, nonce);
		if(b){
			return echostr;
		}
		return "error";
	}
	
	@RequestMapping(value="", method=RequestMethod.POST)
	@ResponseBody
	public String handleMessage(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		return tencentManager.processRequest(request);
	}
	
	@RequestMapping(value="/token", method=RequestMethod.GET)
	@ResponseBody
	public String resetWxToken(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws JSONException{
		if(tencentManager.resetWxToken()){
			return "success";
		}
		return "fail";
	}
	@RequestMapping(value="/ticket", method=RequestMethod.GET)
	@ResponseBody
	public String resetWxTicket(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws JSONException{
		if(JSSDKUtil.getJsApiTicket(GlobalConstant.tencent_wx_token)){
			return "success";
		}
		return "fail";
	}
	
	@RequestMapping(value="/menu", method=RequestMethod.GET)
	@ResponseBody
	public String createMenu(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws JSONException{
		return tencentManager.createMenu();
	}
	
	
	
	
	/**生成永久二维码*/
	@RequestMapping(value="/generatedCode", method=RequestMethod.GET)
	@ResponseBody
	private String generatedCode(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "actionName") String actionName,
			@RequestParam(value = "sceneStr",required = false) String sceneStr,
			@RequestParam(value = "sceneId",required = false) String sceneId,
			HttpSession session, Model model) throws JSONException{
		String result = null;
		
		JSONObject responseJson = codeManager.getTicket(actionName,sceneStr,sceneId);
		if(!responseJson.isNull("ticket")){
			String ticket = responseJson.getString("ticket");
//			String url = responseJson.getString("url");
			result = "{\"code\":200,\"msg\":\"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket+"\"}";
		}else{
			result = "{\"code\":300,\"msg\":\"invalid appid\"}";
		}
		return result;
	}
	
	@RequestMapping(value="bindPrompt", method=RequestMethod.GET)
	@ResponseBody
	public String bindPrompt(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String openid = request.getParameter("openid");
		StringBuffer buffer = new StringBuffer();
		buffer.append("我的账户").append("\n\n\n");
		buffer.append("孵化园加油站").append("\n");
		buffer.append("账户余额：500元").append("\n\n");
		buffer.append("孵化园加油站").append("\n");
		buffer.append("账户余额：700元").append("\n\n\n");
		buffer.append("<a href=\"http://wx.wiz-tech.com.cn/client/listResidualAmount\">点击这里，查询收支明细</a>").append("\n");
		String respContent = buffer.toString();
		
		
		// 回复文本消息
		
		return WxMessageUtil.textMessageToXml(openid,TencentConstant.WX_APP_ID,respContent);
	}
	@RequestMapping(value="/tobind", method=RequestMethod.GET)
	public String toBindLogin(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws JSONException{
		String openId = tencentManager.getOpenId(request.getParameter("code"));
		model.addAttribute("openId", openId);
		log.info("-----------------------"+openId);
//		model.addAttribute("openId", "111");
		return "bind";
	}
	
	@RequestMapping(value="/bind")
	@ResponseBody
	public String bindLogin(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "account") String account,
			@RequestParam(value = "password") String password,
			@RequestParam(value = "openid") String openid,
			HttpSession session, Model model) throws JSONException{
		String result = tencentManager.bindLogin(account, password, openid);
		return result;
	}
	
	@RequestMapping(value="/test")
	@ResponseBody
	public String test(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "wxId") String wxId,
			@RequestParam(value = "phoneNum") String phoneNum,
			HttpSession session, Model model) throws JSONException{
		String result = agentManager.bindAgentMemberByPhone(wxId, phoneNum);
		return result;
	}
	
	/**长链接转短链接*/
	@RequestMapping(value="/shortURL" , method=RequestMethod.POST)
	@ResponseBody
	public String shortURL(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "url") String url,
			HttpSession session, Model model) throws Exception{
		
		String result = tencentManager.shortURL(url);
		
		return result;
	}
	
	
	
	
}
